<?php
/**
 * 后台登陆控制器
 */
 namespace Admin\Controller;
 use Think\Controller;
 
class LoginController extends Controller{
	
	function index(){
		$this->display();
	}
	
	function ckLogin(){
		// if (!M('Admin')->autoCheckToken($_POST)){
			// // 令牌验证错误
			// $this->error('表单令牌验证错误');
			// exit;
		// }
		
		if($_POST['username'] == '' || $_POST['password'] == ''){
			$this->error("用户名和密码不能为空！");
			exit();
		}
		
		$vcode = trim($_POST['verify']);
		if($vcode == '' || !$this->checkVerify($vcode)){
			$this->error("验证码错误");
			exit();
		}
		
		$where = array();
		$where['username'] = I('username');
		$rs  = M("Admin");
		$list= $rs->where($where)->find();
        //使用用户名、密码和状态的方式进行认证
        if (NULL == $list) {
        	oplog('账号不存在',$where['username'],0);
            $this->error('管理员帐号不存在！');
        }
		if ($list['passwd'] != md5(C('SAFE_CODE').trim($_POST['password']))) {
			oplog('密码错误['.$_POST['password'].']',$where['username'],0);
			$this->error('用户密码错误,请重新输入！');
		}
		
		$data['last_login'] = time();
		$data['login_ip'] = get_client_ip();
		$rs->where($where)->setField($data);//修改登录信息
		// 缓存访问权限
		session(C('USER_AUTH_KEY'),$list['id']);
    	session('auser',$list['username']);
    	session("aflag",md5($list['id'].$list['username']));
		
		//保存登陆信息
		//稍后扩展安全登录提示，敬请期待
		oplog('登录',$where['username'],1);
    	$this->success('登录成功！',U('index/index'));
		//redirect(C('GL_ADMIN').'?s=Admin/Index');
	}

	function verify(){//验证码
		$config =    array(
		    'fontSize'    	=> 34,    // 验证码字体大小
		    'length'      	=> 5,     // 验证码位数
		    'imageH'		=> 87,
		    'imageW'		=> 292
		);
        $Verify = new \Think\Verify($config);
		$Verify->entry();
    }
	
	// 检测输入的验证码是否正确，$code为用户输入的验证码字符串
	function checkVerify($code, $id = ''){
	    $verify = new \Think\Verify();
	    return $verify->check($code, $id);
	}
	
	
	//logout
	function logout(){
		if (isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION);
			session_destroy();
        }
		//redirect(C('SC_ADMIN').'?s=Admin/Login');
		echo "<script>top.location.href='".U('login/index')."';</script>";
	}
}
